﻿namespace PmSoft.Utilities;

/// <summary>
/// 比较字符串相似度帮助类
/// </summary>
public class StringSimilarity
{
    /// <summary>
    /// 计算两个句子相似度
    /// </summary>
    /// <param name="words1"></param>
    /// <param name="words2"></param>
    /// <returns></returns>
    public static double CalculateCosineSimilarity(IEnumerable<string> words1, IEnumerable<string> words2)
    {
        var vector1 = new HashSet<string>(words1);
        var vector2 = new HashSet<string>(words2);

        var intersection = new HashSet<string>(vector1);
        intersection.IntersectWith(vector2);

        double dotProduct = intersection.Count;

        double magnitude1 = Math.Sqrt(vector1.Count);
        double magnitude2 = Math.Sqrt(vector2.Count);

        double cosineSimilarity = dotProduct / (magnitude1 * magnitude2);

        return cosineSimilarity;
    }
}
